<?php

namespace App\Http\Controllers\Manage;

use App\Http\Controllers\ApiController;
use App\Http\Requests\HpiStoreRequest;
use App\Http\Requests\HpiUpdateRequest;
use App\Models\MedicalHpi;
use App\Project\Filters\HpiFilter;
use App\Project\Transform;
use App\Transformers\HpiTransformer;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;

class HpiController extends ApiController
{
    /**
     * 项病史项目存储， 含有项病史组信息时一并保存
     * @param \App\Http\Requests\HpiStoreRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function store(HpiStoreRequest $request)
    {
        $input = (new HpiFilter($request))->input();

        $result = MedicalHpi::updateOrCreate(['record_id' => $input['record_id']], $input);

        return $this->response(['id' => $result['id']]);
    }

    /**
     * 现病史编辑
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        $data = null;
        $id   = $request->get('id');

        if ($id > 0) {

            $data = MedicalHpi::findOrFail($id);
        } elseif ($record_id = $request->get('record_id')) {
            $data = MedicalHpi::where(['record_id' => $record_id])->first();
        } else {
            abort(400, '缺失现病史ID，或者病历ID');
        }

        if (empty($data)) {
            throw (new ModelNotFoundException())->setModel(MedicalHpi::class);
        }

        return $this->item($data, new HpiTransformer());
    }

    /**
     * 现病史更新
     * @param \App\Http\Requests\HpiUpdateRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(HpiUpdateRequest $request)
    {
        $where = [];

        if ($id = $request->input('id')) {
            $where['id'] = $id;
        } else {
            $where['record_id'] = $request->input('record_id');
        }

        $input = (new HpiFilter($request))->except(['id', 'record_id']);

        $input = (new Transform())->setArray($input)->convertArrayToJson(
            ['diet', 'normal', 'thyroid', 'adrenal_gland']
        )->get();

        $result = MedicalHpi::where($where)->update($input);

        return $this->responseForUpdate($result);
    }

    public function items(Request $request)
    {
        $category = $request->input('category');

        $data = [];

        if ($category == 'thyroid') {
            $data = app('field')->get('thyroid');
        } elseif ($category == 'adrenal') {
            $data = app('field')->get('adrenal_gland');
        } else {
            $data['thyroid'] = app('field')->get('thyroid');
            $data['adrenal'] = app('field')->get('adrenal_gland');
}

        $type = $request->input('type');

        if ($type && array_key_exists($type, $data)) {
            return $data[$type];
        }

        return $this->hasData($data);
    }
}
